package com.yml;

import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class YamlToMap {
    public static void main(String[] args) {
        String filePath = "D:\\gitee\\test\\hutool\\src\\main\\resources\\application-mysql.yml";
        YamlToMap yamlToMap = new YamlToMap();
        yamlToMap.updateFile(filePath,"Umc@2023abcd1234");
    }

    public void updateFile(String filePath,String newPwd){
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            File file = new File(filePath);
            Map<String, Object> map = mapper.readValue(file, Map.class);
            System.out.println(map);

            Map<String, Object> map2 = (Map<String, Object>)map.get("spring");
            Map<String, Object> map3 = (Map<String, Object>)map2.get("datasource");
            Map<String, Object> map4 = (Map<String, Object>)map3.get("druid");
            String oldPwd = (String) map4.get("password");

            List<String> newList = new ArrayList<>();
            List<String> list =  FileUtil.readLines(filePath, StandardCharsets.UTF_8);
            for(String line : list){
                newList.add(line.replaceAll(oldPwd,newPwd));
            }
            FileUtil.del(filePath);
            FileUtil.appendLines(newList,filePath,StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
